﻿// <copyright project="Salient.SqlServer" file="SqlCmdRunner.cs" company="Sky Sanders">
// This source is a Public Domain Dedication.
// Please see http://spikes.codeplex.com/ for details.   
// Attribution is appreciated
// </copyright> 
// <version>1.0</version>
using System.Collections.Specialized;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;

namespace Salient.SqlServer.Management
{
    /// <summary>
    /// Starting on a new DB fixture
    /// </summary>
    public class SqlCmdRunner
    {
        private SqlConnectionStringBuilder _csBuilder = new SqlConnectionStringBuilder();

        #region Connection String Properties

        public string InitialCatalog
        {
            get { return _csBuilder.InitialCatalog; }
            set { _csBuilder.InitialCatalog = value; }
        }

        public string DataSource
        {
            get { return _csBuilder.DataSource; }
            set { _csBuilder.DataSource = value; }
        }

        public string ConnectionString
        {
            get { return _csBuilder.ConnectionString; }
            set { _csBuilder = new SqlConnectionStringBuilder(value); }
        }

        public bool IntegratedSecurity
        {
            get { return _csBuilder.IntegratedSecurity; }
            set { _csBuilder.IntegratedSecurity = value; }
        }

        public string UserID
        {
            get { return _csBuilder.UserID; }
            set { _csBuilder.UserID = value; }
        }

        public string Password
        {
            get { return _csBuilder.Password; }
            set { _csBuilder.Password = value; }
        }

        #endregion

        public int[] ExecuteScript(StringCollection script)
        {
            return ExecuteScript(script, ExecutionTypes.Default);
        }

        public int[] ExecuteScript(StringCollection script, ExecutionTypes executionTypes)
        {
            using (var conn = new SqlConnection(ConnectionString))
            {
                var serverConn = new ServerConnection(conn);
                var server = new Server(serverConn);

                // ExecutionFailureException

                int[] result;
                try
                {
                    result = server.ConnectionContext.ExecuteNonQuery(script, executionTypes);
                }
                catch (ExecutionFailureException ex)
                {
                    throw ex.InnerException;
                }
                return result;
            }
        }
    }
}